<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }
    </style>
</head>

<body>
    <input type="text" class="msg" placeholder="请输入留言内容">
    <button class="btn">发表留言</button>
    <ul class="cmt"></ul>
    <script>
        let msg = document.getElementsByClassName('msg')[0]
        let btn = document.getElementsByClassName('btn')[0]
        let cmt = document.getElementsByClassName('cmt')[0]

        btn.onclick = () => {
            let val = msg.value //获取文本框的value值
            let newli = document.createElement('li')
            newli.innerText = val || '此人很懒什么都没有留下'
            // cmt.children.length ==cmt.childElementCount 元素节点个数
            if (cmt.childElementCount == 0) {
                return cmt.appendChild(newli)
            }
            // 第一个元素节点儿子cmt.firstElementChild=cmt.children[0]
            cmt.insertBefore(newli, cmt.firstElementChild)
            msg.value = '' //设置文本框的value值
            cmt.childElementCount > 5 ? cmt.removeChild(cmt.lastElementChild) : null

        }
    </script>
</body>

</html>